package com.xingfei.blog.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.dto.BannerDTO;
import com.xingfei.blog.result.ServiceResult;
import com.xingfei.blog.vo.BannerVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 轮播图service
 * Created by chenxingfei on 2017/6/24.
 */
@Service
public class WebBannerService {

    @Autowired
    private BlogBannerService blogBannerService;

    /**
     * 图片访问域名获取
     */
    @Value("${jianyi.imageDomainUrl}")
    private String imageDomainUrl;

    /**
     * 获取轮播图
     *
     * @param bannerVo
     * @return
     */
    public List<BannerVo> listMainBanners(BannerVo bannerVo) {
        BannerDTO bannerDTO = getDTOfromVo(bannerVo);
        if (bannerDTO != null) {
            ServiceResult<List<BannerDTO>> serviceResult = blogBannerService.listBanners(bannerDTO);
            if (serviceResult != null && serviceResult.getCode() == ErrorConstants.RES_SUCCESS) {
                return getListDTOfromListDO(serviceResult.getResult());
            }
        }
        return null;
    }

    /**
     * dto转换为VO
     *
     * @param bannerDTO
     * @return
     */
    private BannerVo getVofromDTO(BannerDTO bannerDTO) {
        BannerVo bannerVo = new BannerVo();
        BeanUtils.copyProperties(bannerDTO, bannerVo);
        return bannerVo;
    }

    /**
     * Vo转换为dto
     *
     * @param bannerVo
     * @return
     */
    private BannerDTO getDTOfromVo(BannerVo bannerVo) {
        BannerDTO bannerDTO = new BannerDTO();
        BeanUtils.copyProperties(bannerVo, bannerDTO);
        return bannerDTO;
    }

    /**
     * list<do>转换为list<dto>
     *
     * @param bannerDOList
     * @return
     */
    private List<BannerVo> getListDTOfromListDO(List<BannerDTO> bannerDOList) {
        if (CollectionUtils.isNotEmpty(bannerDOList)) {
            List<BannerVo> bannerVos = new ArrayList<>();
            bannerDOList.forEach(action -> {
                BannerVo bannerVo = getVofromDTO(action);
                if (bannerVo != null) {
                    bannerVo.setPicPath(imageDomainUrl + bannerVo.getPicPath());
                }
                bannerVos.add(bannerVo);

            });
            return bannerVos;
        }
        return null;
    }


}
